package com.emm.yixun.system.service.impl.notice.subscribe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.NoticeEntity;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.system.service.impl.manage.SysNoticeManage;
import com.emm.yixun.system.service.notice.subscribe.SubscribeDelaySignedNoticeFacade;

/**
 * 认购延期签约审批消息
 * @author jhsong
 *
 */
@Service("subscribeDelaySignedNoticeFacade")
@WebService(name="com.emm.yixun.system.service.SubscribeDelaySignedNoticeFacade")
public class SubscribeDelaySignedNoticeFacadeImpl implements SubscribeDelaySignedNoticeFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	@Autowired
	private BusinessAbnormaService businessAbnormaService;
	
	@Override
	public Response<Boolean> createSubscribeDelaySignedNotice(NoticeEntity noticeEntity) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			// 实体对象
			Subscribe subscribe_yqqy = subscribeService.selectById(noticeEntity.getNoticeBusinessId());
			// 项目
			ProjectDto proDto = new ProjectDto();
			proDto.setProjectCode(subscribe_yqqy.getProjectCode());
			Project project = projectService.selectByDto(proDto);
			// 发起人,异常流程记录的创建人
			List<User> userList = new ArrayList<User>();
			User user_fqr = new User();
			BusinessAbnormaDto businessAbnormaDto=new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(subscribe_yqqy.getId());
			businessAbnormaDto.setProcInstId(noticeEntity.getProcessInstanceId());
			BusinessAbnorma businessAbnorma = businessAbnormaService.selectByDto(businessAbnormaDto);
			if(null != businessAbnorma){
				user_fqr = userService.selectById(businessAbnorma.getCreateUserId());
				userList.add(user_fqr);
			}
			String userName_fqr = user_fqr==null?"":user_fqr.getUserName();
			// 经纪人
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(subscribe_yqqy.getId());
			transactionRelationDto.setMerchantId(subscribe_yqqy.getMerchantId());
			transactionRelationDto.setProjectCode(subscribe_yqqy.getProjectCode());
			List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
			if (null != transactionRelationList && transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if(null != user_fqr && null != user){
						if(null != user_fqr.getId()){
							if(!user_fqr.getId().equals(user.getId())){
								userList.add(user);
							}
						}else{
							userList.add(user);
						}
					}
				}
			}
			
			if(userList.size() > 0){
				assembleSubscribeDelaySignedNotice(subscribe_yqqy, userList, "1", null, noticeEntity.getTimeType(), noticeEntity.getProcessInstanceId());
			}
			
			// 营销负责人【销管经理】
			List<User> userList_yqqy = new ArrayList<User>();
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(project.getProjectCode());
			List<ProjectSetting> pObj = projectSettingService.selectListByDto(pDto);
			User saleLeaderUser = userService.selectById(pObj.get(0).getMaLeader());
			userList_yqqy.add(saleLeaderUser);
			//逆向流程，从业务异常表获取审核状态
			if(userList_yqqy.size() > 0 && "3".equals(businessAbnorma.getAuditStatus())){
				assembleSubscribeDelaySignedNotice(subscribe_yqqy, userList_yqqy, "2", userName_fqr, noticeEntity.getTimeType(), noticeEntity.getProcessInstanceId());
			}
			response.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			response.setSuccess(false);
			logger.error("组装认购延期签约消息异常:{}",e);
		}
		return response;
	}
	
	/**
	 * 组装【认购延期签约】消息
	 * 
	 * @param subscribe 业务对象
	 * @param userList 用户列表
	 * @param type 1 审核结果 2 报备信息
	 * @param userName 发起人
	 * @param timeType 延期时间类型
	 * @param processInstanceId 流程ID
	 * @return
	 */
	public String  assembleSubscribeDelaySignedNotice(Subscribe subscribe_yqqy, List<User> userList, String type, String userName_fqr, String timeType, String processInstanceId){
		Map<String, String> noticeParamMap = new HashMap<String, String>();
		try {
			// 房源
			String proName = "";
			if (subscribe_yqqy.getRoomId() != null && !"".equals(subscribe_yqqy.getRoomId())) {
				ProjectRoom project = projectRoomService.selectById(subscribe_yqqy.getRoomId());
				if (project != null) {
					proName = project.getCombinedName();
				}
			}
			// 客户
			String cusName = "";
			Customer customer = customerService.selectById(subscribe_yqqy.getCustomerId());
			if (customer != null) {
				cusName = customer.getCustomerName();
			}
			//逆向流程，从业务异常表获取审核状态
			BusinessAbnormaDto businessAbnormaDto=new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(subscribe_yqqy.getId());
			businessAbnormaDto.setProcInstId(processInstanceId);
			BusinessAbnorma businessAbnorma = businessAbnormaService.selectByDto(businessAbnormaDto);
			// 延期签约流程, 获取字典表dictionary_value = 'NT34' 的消息模板
			// 消息模板: 延期签约审核结果【${auditStatus}】房号：${roomName}；客户：${customer}
			String msgTemp = "";
			String yqqy = "";
			if("1".equals(timeType)){
				yqqy = "(15天内)";
			}else if("2".equals(timeType)){
				yqqy = "(15~30天)";
			}else if("3".equals(timeType)){
				yqqy = "(30天以上)";
			}
			if("1".equals(type)){
				msgTemp = "延期签约"+yqqy+"审核结果【${auditStatus}】房号：${roomName}；客户：${customer}；";
			}else{
				msgTemp = "【延期签约"+yqqy+"】：${roomName}；客户：${customer}；发起人：${userName}【审核通过】";
			}
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT34");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if("1".equals(type)){
				if (dic != null) {
					msgTemp = dic.getDictionaryName();
				}
				sendMsg = msgTemp
						.replace("${auditStatus}", AuditStatusEnum.getByNo(businessAbnorma.getAuditStatus()).getDes())
						.replace("${roomName}", proName).replace("${customer}", cusName);
			}else{
				sendMsg = msgTemp
						.replace("${roomName}", proName)
						.replace("${customer}", cusName)
						.replace("${userName}", userName_fqr);
			}
			// 创建提醒消息及消息发送人信息
			noticeParamMap.put("noticeDicId",  dic.getId()+"");
			noticeParamMap.put("noticeTempType", "NT34");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "延期签约流程审核结果");
			noticeParamMap.put("merchantId", String.valueOf(subscribe_yqqy.getMerchantId()));
			noticeParamMap.put("userCode", subscribe_yqqy.getUserCode());
			noticeParamMap.put("accessCode", subscribe_yqqy.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(subscribe_yqqy.getCreateUserId()));
			noticeParamMap.put("customerId", String.valueOf(subscribe_yqqy.getCustomerId()));
			noticeParamMap.put("businessId", String.valueOf(subscribe_yqqy.getId()));
			noticeParamMap.put("projectCode", subscribe_yqqy.getProjectCode());
			if("1".equals(type)){
				noticeParamMap.put("tempType", "2");
			}else{
				noticeParamMap.put("tempType", "3");
			}
			noticeParamMap.put("msgOrder", "1");
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(subscribe_yqqy.getRoomId()));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, proName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,cusName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			replaceValuesMap.put(MsgUtil.BUSINESS_ID, subscribe_yqqy.getId()+"");
			replaceValuesMap.put(MsgUtil.NEXT_NODE_ID, "");
			replaceValuesMap.put(MsgUtil.PROCESS_INSTANCE_ID, processInstanceId+"");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
	    	sysNoticeManage.createNoticeWithNoticeTemp(noticeParamMap, userList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("组装认购延期签约消息异常:{}",e);
		}
		return ResultEnum.SUCCESS.getNo();
	}
	
}
